package com.rgs.ssm.controller;

import com.github.pagehelper.PageInfo;
import com.rgs.ssm.domain.Role;
import com.rgs.ssm.domain.UserInfo;
import com.rgs.ssm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @create 2021-02-18 18:59
 **/
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 分页查询所有用户信息
     * @param page
     * @param size
     * @return
     */
    @RequestMapping("/findAll.do")
    public ModelAndView findAll(@RequestParam(name = "page",required = true,defaultValue = "1")Integer page,@RequestParam(name = "size",required =true,defaultValue = "5")Integer size){
        ModelAndView mv = new ModelAndView();
        List<UserInfo> users = userService.findAll(page, size);
        PageInfo pageInfo = new PageInfo(users);
        mv.addObject("userList",pageInfo);
        mv.setViewName("user-list");
        return mv;
    }

    /**
     * 根据id，查看指定用户详情（包括用户的角色信息，以及角色信息中的权限信息）
     * @param userId
     * @return
     */
    @RequestMapping("/findById.do")
    public ModelAndView findById(@RequestParam(name = "id",required = true)Integer userId){
        ModelAndView mv = new ModelAndView();
        UserInfo user = userService.findById(userId);
        System.out.println(user);
        mv.addObject("user",user);
        mv.setViewName("user-show");
        return mv;
    }

    /**
     * 处理添加用户的请求
     * @param userInfo
     * @return
     */
    @RequestMapping("/save.do")
    public String saveUser(UserInfo userInfo){
        userService.saveUser(userInfo);
        return "redirect:/user/findAll.do";
    }

    /**
     * 去添加页面，并查询用户没有的角色
     * 1.查到对应id的用户
     * 2.在user_role表中，查到该用户没有的角色，并显示在页面上供用户添加
     */
    @RequestMapping("/findUserByIdAndAllRole.do")
    public ModelAndView findUserByIdAndAllRole(@RequestParam(name = "id",required = true)Integer userId){
        ModelAndView mv = new ModelAndView();
        UserInfo userInfo = userService.findById(userId);
        List<Role> otherList = userService.findByIdOtherRole(userId);
        mv.addObject("user",userInfo);
        mv.addObject("roleList",otherList);
        mv.setViewName("user-role-add");
        return mv;
    }

    /**
     * 给用户添加角色
     * 在user_role表中进行添加UserId和roleId
     * @param userId 用户ID
     * @param roleIds 待添加的角色ID 数组
     * @return
     */
    @RequestMapping("/addRoleToUser.do")
    public String addRoleToUser(@RequestParam(name = "userId",required = true) Integer userId,@RequestParam(name = "ids",required = true) Integer[] roleIds){
        userService.addRoleToUser(userId,roleIds);
        return "redirect:/user/findAll.do";
    }




}
